package com.hxkj.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxkj.dao.*;
import com.hxkj.domain.enums.ArticleExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.service.ArticleService;
import com.hxkj.service.ColumnService;
import com.hxkj.utils.DateFormatUtils;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章实现类
 * <p>
 * created by zzx on 2018/6/6.
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private ArticleTagsDao articleTagsDao;

    @Autowired
    private TagsDao tagsDao;
    @Autowired
    private ColumnDao columnDao;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private ContentMappingDao contentMappingDao;

    @Autowired
    private ContentDao contentDao;

    @Override
    public PageInfo<Article> get(Article article, PageTo pageParam) throws Exception {
        Page<Article> page = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        articleDao.get(article);
        PageInfo<Article> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

    @Override
    public PageInfo<Article> getArticleList(Article article, PageTo pageParam) throws Exception {
        try {
            //查询文章列表（包含文章回收站列表、文章审核列表、文章管理列表）
            if (article.getColumnId() != null) {
                Column column = new Column();
                column.setSiteId(article.getSiteId());
                column.setColumnId(article.getColumnId());
                List<Column> columnList = columnService.getAllColumnList(column);
                StringBuffer sb = new StringBuffer();
                if (columnList != null && columnList.size() > 0) {
                    for (Column c : columnList) {
                        sb.append(",").append(c.getColumnId());
                    }
                }
                if (columnList != null && columnList.size() > 0) {
                    article.setColumnIds(sb.toString());
                } else {
                    article.setColumnIds(String.valueOf(article.getColumnId()));
                }
            }
            if (null == pageParam || null == pageParam.getPageSize() || null == pageParam.getPageNum()) {
                pageParam.setPageNum(1);
                pageParam.setPageSize(10);
            }
            if (pageParam.getPageNum() == 0){
                pageParam.setPageNum(1);
            }
            Page<Article> page = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            article.setCount(pageParam.getPageSize());
            articleDao.getArticleList(article);
            PageInfo<Article> pageInfo = new PageInfo<>(page);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询文章列表错误");
        }
        return new PageInfo<>();
    }

    @Override
    public PageInfo<Article> getArticleListByTags(Article article, PageTo pageTo) {
        try {
            //查询文章列表（包含文章回收站列表、文章审核列表、文章管理列表）

            if (null == pageTo || null == pageTo.getPageSize() || null == pageTo.getPageNum()) {
                pageTo.setPageNum(1);
                pageTo.setPageSize(10);
            }
            if (pageTo.getPageNum() == 0){
                pageTo.setPageNum(1);
            }
            Page<Article> page = PageHelper.startPage(pageTo.getPageNum(), pageTo.getPageSize());
            article.setCount(pageTo.getPageSize());
            articleDao.getArticleListByTags(article);
            PageInfo<Article> pageInfo = new PageInfo<>(page);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询文章列表错误");
        }
        return new PageInfo<>();
    }

    //递归调用获取文章分类的树结构
    private Article initTree(Article article) throws Exception {
        List<Column> columnList = new ArrayList<>();
        Column column = new Column();
        column.setParentColumnId(article.getColumnId());
        column.setSiteId(article.getSiteId());
        if (article.getColumnId() != null) {
            columnList = columnDao.getColumnList(column);
        }
        StringBuffer sb = new StringBuffer();

        if (columnList != null && columnList.size() != 0) {
            String columnIds = "";
            for (Column auf : columnList) {
                article.setColumnId(auf.getColumnId());
                initTree(article);
                columnIds = columnIds + "," + auf.getColumnId();
            }
            article.setColumnIds(columnIds);
        } else {
            if (article.getColumnId() != null) {
                article.setColumnIds(article.getColumnId() + "");
            }
        }
        return article;
    }


    @Override
    public ResultDataStruct<Article> getArticle(Article article) throws Exception {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        Article art;
        try {
            //查询一条文章信息
            art = articleDao.get(article.getArticleId());
            Content content = new Content();
            content.setSiteId(art.getSiteId());
            content.setArticleId(art.getArticleId());
            List<Content> contentList = contentDao.getContent(content);
            if (contentList != null && contentList.size() > 0) {
                content = contentList.get(0);
            }
            art.setContent(content);

            ContentMapping contentMapping = new ContentMapping();
            contentMapping.setColumnId(art.getColumnId());
            List<ContentMapping> contentMappingList = contentMappingDao.getContentMappingList(contentMapping);
            if (contentMappingList != null && contentMappingList.size() > 0) {
                art.setContentMappingList(contentMappingList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_GET_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_GET_ERRO.getMsg());
            return result;
        }
        result.setData(art);
        return result;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessageStruct updateArticle(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        //获取当前时间 + 3个月得 时间戳
        Long createTime = DateFormatUtils.dateFormatMonth(3);
        Content content = article.getContent();
        content.setSiteId(article.getSiteId());
        content.setArticleId(article.getArticleId());
        Article art = new Article();
        art.setArticleId(article.getArticleId());
        art.setHeadline(article.getHeadline());
        art.setSiteId(article.getSiteId());
        art.setCreateTime(createTime);


        try {
            //判断文章是否重复（3个月内的文章标题不允许重复，3个月后的可以重复） 定义一个3个月以后的时间做条件
            List<Article> artList = articleDao.getArticleHeadline(art);
            if (artList.size() > 0) {
                //如果在3个月内能查到 文章标题 相同的文章，则抛出 文章标题重复
                result.setCode(ArticleExceptionEnum.ARTICLE_REPETITION.getCode());
                result.setMessage(ArticleExceptionEnum.ARTICLE_REPETITION.getMsg());
                return result;
            }
            Article article1 = articleDao.get(article.getArticleId());
            long columnId = article.getColumnId();
            //修改一篇文章
            articleDao.update(article);
            long columnId1 = article1.getColumnId();
            if (columnId != columnId1) {
                Content cont = new Content();
                cont.setArticleId(article.getArticleId());
                cont.setSiteId(article.getSiteId());
                contentDao.removeContentByArticleId(article.getArticleId());
            } else {
                if (content.getId() != null) {
                    contentDao.update(content);
                } else {
                    contentDao.saveContent(content);
                }
            }

            Article newArticle = articleDao.get(article.getArticleId());
            if (StringUtils.isBlank(newArticle.getTags())) {
                return result;
            }
            //清空关于此篇文章的tags关联(下面的业务会进行重新关联)
            ArticleTags ArticleTags = new ArticleTags();
            ArticleTags.setArticleId(article.getArticleId());
            articleTagsDao.delete(ArticleTags);

            //解析 tags 标签 成 String数组
            String[] tags = newArticle.getTags().split(",|，|、");
            for (String tag : tags) {

                //判断tag在 tags 中是否存在，如果不存在则在 tags标签库中新增
                List<Tags> list = tagsDao.getTagsByName(tag, article.getSiteId());
                Tags t = new Tags();
                t.setTagsName(tag);
                t.setSiteId(article.getSiteId());
                if (list.size() == 0) {
                    tagsDao.saveTags(t);
                } else {
                    t.setTagsId(list.get(0).getTagsId());
                }
                //文章 与 tags 进行关联
                ArticleTags artTags = new ArticleTags();
                artTags.setArticleId(article.getArticleId());
                artTags.setTagsId(t.getTagsId());
                artTags.setCreateTime(System.currentTimeMillis());
                articleTagsDao.save(artTags);

                //根据tags与文章的中间表 查出 tags 被引用了多少次
                ArticleTags tsg = new ArticleTags();
                tsg.setTagsId(t.getTagsId());
                List<ArticleTags> tagSize = articleTagsDao.get(tsg);
                //对tags 的的 使用次数进行更新
                t.setQuoteCount(tagSize.size());
                tagsDao.modifyTags(t);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getMsg());
            throw e;
        }
        return result;
    }

    /**
     * 文章恢复
     */
    @Override
    public ResultMessageStruct articleAudit(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        String[] articleIds = article.getArticleIds().split(",|，|、");
        try {
            for (String articleId : articleIds) {
                article.setArticleId(Long.valueOf(articleId));
                article.setDelTag(0);
                //设置恢复到文章列表的时间
                article.setUpdateTime(System.currentTimeMillis());
                //批量回收站恢复文章
                articleDao.update(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_REMOVE_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_REMOVE_ERRO.getMsg());
            throw e;
        }
        return result;
    }

    @Override
    public ResultMessageStruct articleRecover(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        String[] articleIds = article.getArticleIds().split(",");
        try {
            for (String articleId : articleIds) {
                article.setArticleId(Long.valueOf(articleId));
                //设置修改时间
                article.setUpdateTime(System.currentTimeMillis());
                //批量设置文章推荐/ 审核
                articleDao.updateArticleRecover(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getMsg());
            throw e;
        }
        return result;
    }

    @Override
    public ResultMessageStruct articleStick(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        String[] articleIds = article.getArticleIds().split(",");
        try {
            for (String articleId : articleIds) {
                article.setArticleId(Long.valueOf(articleId));
                //设置修改时间
                article.setUpdateTime(System.currentTimeMillis());
                //置顶/取消置顶
                articleDao.updateArticleStick(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_MODIFY_ERRO.getMsg());
            throw e;
        }
        return result;
    }

    @Override
    public ResultMessageStruct removerArticle(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        String[] articleIds = article.getArticleIds().split(",");
        try {
            for (String articleId : articleIds) {
                Article art = new Article();
                art.setArticleId(Long.valueOf(articleId));
                art.setDelTag(1);
                //设置删除到回收站的时间
                art.setUpdateTime(System.currentTimeMillis());
                //批量移除文章至回收站
                articleDao.update(art);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_REMOVE_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_REMOVE_ERRO.getMsg());
            throw e;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDataStruct saveArticle(Article article) throws Exception {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        Content content = article.getContent();
        //获取当前时间 + 3个月得 时间戳
        Long createTime = DateFormatUtils.dateFormatMonth(3);
        Article art = new Article();
        art.setHeadline(article.getHeadline());
        art.setCreateTime(createTime);
        art.setSiteId(article.getSiteId());

        //判断文章是否重复（3个月内的文章标题不允许重复，3个月后的可以重复） 定义一个3个月以后的时间做条件
        List<Article> artList = articleDao.getArticleHeadline(art);
        if (artList.size() > 0) {
            //如果在3个月内能查到 文章标题 相同的文章，则抛出 文章标题重复
            result.setCode(ArticleExceptionEnum.ARTICLE_REPETITION.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_REPETITION.getMsg());
            return result;
        }
        //发布一篇文章
        articleDao.save(article);
        if (content != null) {
            content.setArticleId(article.getArticleId());
            content.setSiteId(article.getSiteId());
            //保存文章的扩展内容
            contentDao.saveContent(content);
            article.setContent(content);
        }
        result.setData(article);

        if (StringUtils.isBlank(article.getTags())) {
            return result;
        }

        // 解析 tags 标签 成 String数组
        String[] tags = article.getTags().split(",|，|、");
        for (String tag : tags) {
            //判断tag在 tags 中是否存在，如果不存在则在 tags标签库中新增
            List<Tags> list = tagsDao.getTagsByName(tag, article.getSiteId());
            Tags t = new Tags();
            t.setTagsName(tag);
            t.setSiteId(article.getSiteId());
            if (list.size() == 0) {
                tagsDao.saveTags(t);
            } else {
                t.setTagsId(list.get(0).getTagsId());
            }

            // 文章 与 tags 进行关联
            ArticleTags artTags = new ArticleTags();
            artTags.setArticleId(article.getArticleId());
            artTags.setTagsId(t.getTagsId());
            artTags.setCreateTime(System.currentTimeMillis());
            articleTagsDao.save(artTags);

            // 根据tags与文章的中间表 查出 tags 被引用了多少次
            ArticleTags tsg = new ArticleTags();
            tsg.setTagsId(t.getTagsId());
            List<ArticleTags> tagSize = articleTagsDao.get(tsg);

            //对tags 的的 使用次数进行更新
            t.setTagsId(t.getTagsId());
            t.setQuoteCount(tagSize.size());
            tagsDao.modifyTags(t);
        }
        return result;
    }

    @Override
    public ResultMessageStruct deleteArticle(Article article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        String[] articleIds = article.getArticleIds().split(",");
        try {
            //遍历文章id数组
            for (String articleId : articleIds) {
                //批量删除回收站文章
                int i = articleDao.delete(Long.valueOf(articleId));
                if (i > 0) {
                    contentDao.removeContentByArticleId(Long.valueOf(articleId));//删除扩展内容
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ArticleExceptionEnum.ARTICLE_DELETE_ERRO.getCode());
            result.setMessage(ArticleExceptionEnum.ARTICLE_DELETE_ERRO.getMsg());
            return result;
        }
        return result;
    }

    @Override
    public ResultDataStruct getArticle1(Article article) throws Exception {
        ResultDataStruct resul = new ResultDataStruct();
        List<Article> ArticleList;
        try {
            article.setUpdateTime(DateFormatUtils.getMillisecondsBeforeDay(30));
            ArticleList = articleDao.getArticle1(article);
        } catch (Exception e) {
            e.printStackTrace();
            resul.setCode(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getCode());
            resul.setMessage(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getMsg());
            return resul;
        }
        resul.setData(ArticleList);

        return resul;
    }

    @Override
    public ResultDataStruct getArticle3(Article article) throws Exception {
        ResultDataStruct resul = new ResultDataStruct();
        List<Article> ArticleList;
        try {
            ArticleList = articleDao.getArticle3(article);
        } catch (Exception e) {
            e.printStackTrace();
            resul.setCode(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getCode());
            resul.setMessage(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getMsg());
            return resul;
        }
        resul.setData(ArticleList);

        return resul;
    }

    @Override
    public ResultDataStruct<List<Article>> getArticle4(Article article) throws Exception {
        ResultDataStruct<List<Article>> resul = new ResultDataStruct();
        List<Article> ArticleList;
        try {
            ArticleList = articleDao.getArticle4(article);
        } catch (Exception e) {
            e.printStackTrace();
            resul.setCode(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getCode());
            resul.setMessage(ArticleExceptionEnum.ARTICLE_GETARTICLE1_ERRO.getMsg());
            return resul;
        }
        resul.setData(ArticleList);

        return resul;
    }

    @Override
    public ResultDataStruct getArticleMarket(Article article) throws Exception {
        ResultDataStruct resul = new ResultDataStruct();
        List<Article> ArticleList;
        try {
            ArticleList = articleDao.getArticleMarket(article);
        } catch (Exception e) {
            e.printStackTrace();
            resul.setCode(ArticleExceptionEnum.ARTICLE_GETARTICLEMARKET_ERRO.getCode());
            resul.setMessage(ArticleExceptionEnum.ARTICLE_GETARTICLEMARKET_ERRO.getMsg());
            return resul;
        }
        resul.setData(ArticleList);

        return resul;
    }

    @Override
    public ResultDataStruct getHotArticle(Article article) throws Exception {
        ResultDataStruct resul = new ResultDataStruct();
        List<Article> ArticleList;
        try {
            ArticleList = articleDao.getHotArticle(article);
        } catch (Exception e) {
            e.printStackTrace();
            resul.setCode(ArticleExceptionEnum.ARTICLE_GETHOTARTICLE_ERRO.getCode());
            resul.setMessage(ArticleExceptionEnum.ARTICLE_GETHOTARTICLE_ERRO.getMsg());
            return resul;
        }
        resul.setData(ArticleList);

        return resul;
    }

    @Override
    public ResultDataStruct<Integer> getRightsCount(Article article) throws Exception {
        ResultDataStruct<Integer> result = new ResultDataStruct();
        Integer count;
        try {
            count = articleDao.getRightsCount(article);
            result.setCode(null);
            result.setData(count);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }


    }

    @Override
    public ResultDataStruct<Article> getPreArticle(Article article) {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        try {
            Article preArticle = articleDao.getPreArticle(article);
            result.setCode(200);
            result.setData(preArticle);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    public ResultDataStruct<Article> getNextArticle(Article article) {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        try {
            Article nextArticle = articleDao.getNextArticle(article);
            result.setCode(200);
            result.setData(nextArticle);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public List<Article> getArticleListByParam(Article article) throws Exception {
        List<Article> articleList;
        try {
            putColumnIds(article);
            articleList = articleDao.getArticleListByParam(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return articleList;
    }

    private void putColumnIds(Article article) throws Exception {
        if (StringUtils.isNotBlank(article.getColumnIds())) {
            String[] colIds = article.getColumnIds().split(",");
            StringBuilder columnIds = new StringBuilder();
            for (String columnId : colIds) {
                article.setColumnId(Long.valueOf(columnId));
                if (StringUtils.isEmpty(columnIds)) {
                    columnIds = getColumnIds(article);
                } else {
                    columnIds = columnIds.append(",").append(getColumnIds(article));
                }
            }
            article.setColumnIds(columnIds.toString());
        } else if (article.getColumnId() != null) {
            String columnIds = getColumnIds(article).toString();
            article.setColumnIds(columnIds);
        }
    }

    private StringBuilder getColumnIds(Article article) throws Exception {
        Column column = new Column();
        column.setColumnId(article.getColumnId());
        column.setSiteId(article.getSiteId());
        List<Column> columnList = getColumnIds(column);
        StringBuilder columnIds = new StringBuilder();
        for (int i = 0; i < columnList.size(); i++) {
            columnIds = columnIds.append(String.valueOf(columnList.get(i).getColumnId())).append(",");
        }
        columnIds = columnIds.append(String.valueOf(article.getColumnId()));
        return columnIds;
    }


    @Override
    public List<Tags> getTagsListByHotArticle(Article article) throws Exception {
        List<Tags> tagsList;
        try {
            putColumnIds(article);
            tagsList = articleDao.getHotArticleAsTagsList(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return tagsList;
    }

    @Override
    public void modifyArticleAsPath(Article article) throws Exception {
        try {
            articleDao.modifyArticleAsPath(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取曝光和咨询文章列表  chenfangzhou
    @Override
    public List<Article> getrightsArticlesByParam(Article article) throws Exception {
        try {
            List<Article> rightsArticles = articleDao.getrightsArticlesByParam(article);
            return rightsArticles;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDataStruct<Article> modifyHeat(Article article) throws Exception {
        ResultDataStruct<Article> resultDataStruct = new ResultDataStruct<>();
        if (article.getHeat() == null) {
            article = articleDao.get(article.getArticleId());
        }
        if (article == null) {
            resultDataStruct.setCode(ArticleExceptionEnum.ARTICLE_NOT_EXIST.getCode());
            resultDataStruct.setMessage(ArticleExceptionEnum.ARTICLE_NOT_EXIST.getMsg());
            return resultDataStruct;
        }
        //Mr.zheng:每次调用将热度值+1
        article.setHeat(article.getHeat() + 1);
        int count = articleDao.modifyHeat(article);
        if (count == 0) {
            resultDataStruct.setCode(ArticleExceptionEnum.ARTICLE_UPDATE_HEAT_ERROR.getCode());
            resultDataStruct.setMessage(ArticleExceptionEnum.ARTICLE_UPDATE_HEAT_ERROR.getMsg());
            return resultDataStruct;
        }
        resultDataStruct.setCode(200);
        resultDataStruct.setData(article);
        return resultDataStruct;
    }


    public ResultDataStruct<List<Article>> searchArticle(Article article) throws Exception {
        ResultDataStruct<List<Article>> listResultDataStruct = new ResultDataStruct<>();
        List<Article> articleList = articleDao.searchArticle(article);
        listResultDataStruct.setData(articleList);
        return listResultDataStruct;
    }

    @Override
    public List<Article> getArticleListByTime(Article article) throws Exception {
        List<Article> articleList = null;
        try {
            articleList = new ArrayList<>();
            articleList = articleDao.getArticleListByTime(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleList;
    }

    /**
     * 自定义标签,获取相关推荐文章/随机文章
     *
     * @param article
     * @return
     * @throws Exception
     */
    @Override
    public List<Article> getCorrelationArticle(Article article) throws Exception {
        try {
            //获取随机文章
            if ("random".equals(article.getSort())) {
                List<Article> list = new ArrayList<>();
                //获取总的可用的文章篇数
                Integer totalCount = articleDao.getRightsCount(article);
                if (totalCount <= article.getCount()) {
                    //获取所有可用文章
                    return articleDao.getAllArticleList(article);
                }
                do {
                    list = articleDao.getRandomArticle(article);
                } while (list.size() < article.getCount());
                return list;
            }
            return articleDao.getCorrelationArticle(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public ResultDataStruct<Article> getArticleByTempletId(Article article) {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        try {
            List<Article> articleList = articleDao.getArticleByTempletId(article);
            if (articleList != null && articleList.size() != 0) {
                article = articleList.get(0);
                result.setData(article);
                result.setCode(200);
                return result;
            }
            result.setCode(401);
            result.setMessage("没有文章引用该详情模板");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    /***
     * 获取最近一个月内的文章
     **/
    @Override
    public List<Article> getArticleInMonth(Article article) throws Exception {
        try {
            article.setUpdateTime(DateFormatUtils.getMillisecondsBeforeDay(30));
            return articleDao.getArticleInMonth(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /***
     * 日排行
     **/
    @Override
    public List<Article> getDailyArticleList(Article article) {
        try {
            //获取北京时间今日0点的时间戳
            long ONE_DAY_MILLIS = 24L * 3600 * 1000;
            long timeZone = 8L * 3600 * 1000;
            long timeStamp = System.currentTimeMillis();
            long todayStartTime = timeStamp - (timeStamp + timeZone) % (ONE_DAY_MILLIS);
            article.setCreateTimeStart(todayStartTime);
            return articleDao.getDailyArticleList(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /***
     * 周排行
     **/
    @Override
    public List<Article> getWeeklyArticleList(Article article) {
        try {
            article.setUpdateTime(DateFormatUtils.getMillisecondsBeforeDay(7));
            return articleDao.getWeeklyArticleList(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private List<Column> getColumnIds(Column column) throws Exception {
        List<Column> columns = columnDao.getColumnByParentColumnId(column.getColumnId());
        List<Column> columnList = new ArrayList<>();
        if (columns != null && columns.size() > 0) {
            columnList.addAll(columns);
            for (Column col : columns) {
                columnList.addAll(getColumnIds(col));
            }
        }
        return columnList;
    }

    @Override
    public ResultDataStruct<List<Article>> selectArticleForUserCenter() {
        ResultDataStruct<List<Article>> result = new ResultDataStruct<>();
        List<Article> list = articleDao.selectArticleForUserCenter();
        if (list == null || list.size() == 0) {
            result.setCode(601);
            result.setMessage("没有热门文章记录");
            return result;
        }
        result.setCode(200);
        result.setMessage("success");
        result.setData(list);
        return result;
    }

    /**
     * 外汇网中的相关文章推荐 --根据该篇文章相同的tags标签获取文章
     *
     * @param article
     * @return
     * @throws Exception
     */
    @Override
    public List<Article> getRecommendationArticle(Article article) throws Exception {

        try {
            return articleDao.getRecommendationArticle(article);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据文章id字符串获取文章,用于软件下载,
     * 增加了文章的扩展属性
     *
     * @param article
     * @return
     */
    @Override
    public List<Article> getArticleByIds(Article article) throws Exception {
        try {
            List<Article> articleList = articleDao.getArticleByIds(article);
            //判断该文章所在分类是否有扩展属性
            ContentMapping contentMapping = new ContentMapping();
            contentMapping.setColumnId(article.getColumnId());
            List<ContentMapping> list = contentMappingDao.getContentMappingList(contentMapping);
            if (list != null && list.size() > 0) {
                //该分类有扩展属性
                setContentMap(article, list);
            }

            return articleList;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void setContentMap(Article article, List<ContentMapping> contentMappingList) throws Exception {
        Content content = new Content();
        content.setArticleId(article.getArticleId());
        content.setSiteId(article.getSiteId());
        content = contentDao.getContent(content).get(0);
        String json = JSONObject.toJSONString(content);
        JSONObject jsonObject = JSONObject.parseObject(json);
        Map<String, String> map = new HashMap<>();
        for (ContentMapping Mapping : contentMappingList) {
            map.put(Mapping.getCustomName(), jsonObject.get(Mapping.getContentName()).toString());
        }
        article.setMap(map);

    }

    @Override
    public ResultDataStruct<Article> getArticleByArticleId(Long articleId) throws Exception {
        ResultDataStruct<Article> result = new ResultDataStruct<>();
        try {
            Article entity = articleDao.get(articleId);
            result.setCode(200);
            result.setMessage("success");
            result.setData(entity);
        } catch (Exception e) {
            result.setCode(ArticleExceptionEnum.ARTICLE_GET_ERRO.getCode());
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
